package com.open.capacity.reimburse.service.impl;

import com.open.capacity.common.FileService;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.reimburse.dao.SysFileinfoAuthorizeDao;
import com.open.capacity.reimburse.entity.SysFilefolder;
import com.open.capacity.reimburse.entity.SysFileinfoAuthorize;
import com.open.capacity.reimburse.util.FileUtil;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.model.SysFile;
import com.open.capacity.user.service.SysFileService;
import com.open.capacity.utils.SysUserUtil;
import com.open.capacity.workflow.model.WFProcessinstance;
import com.open.capacity.workflow.service.WFProcessinstanceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.entity.SysFileinfo;
import com.open.capacity.reimburse.dao.SysFileinfoDao;
import com.open.capacity.reimburse.service.SysFileinfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class SysFileinfoServiceImpl implements SysFileinfoService {

    @Autowired
    private SysFileinfoDao sysFileinfoDao;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private FileService fileService;

    @Autowired
    private SysFileinfoAuthorizeDao fileinfoAuthorizeDao;


    /**
     * 添加
     *
     * @param sysFileinfo
     */
    public int save(SysFileinfo sysFileinfo) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        //sysFileinfo.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        sysFileinfo.setCreateTime(new Date());
        sysFileinfo.setCreateUserid(loginUser.getId());
        sysFileinfo.setCreateUsername(loginUser.getRealName());
        sysFileinfo.setUpdateTime(new Date());
        sysFileinfo.setUpdateUserid(loginUser.getId());
        sysFileinfo.setUpdateUsername(loginUser.getRealName());
        sysFileinfo.setStatus(-1);

        return sysFileinfoDao.save(sysFileinfo);
    }

    /**
     * 修改
     *
     * @param sysFileinfo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(SysFileinfo sysFileinfo) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();

        sysFileinfo.setUpdateTime(new Date());
        sysFileinfo.setUpdateUserid(loginUser.getId());
        sysFileinfo.setUpdateUsername(loginUser.getRealName());
        //sysFileinfo.setStatus(1);

//        List<SysFile> files = sysFileService.findByFolderId(sysFileinfo.getId());
//        if (CollectionUtils.isNotEmpty(files)) {
//            files.forEach(item -> {
//                item.setStatus(1);
//                sysFileService.updateStatus(item.getId(), 1);
//            });
//        }

        return sysFileinfoDao.update(sysFileinfo);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return sysFileService.updateStatus(id, -1);
    }

    @Override
    public int restore(String id) {
        return sysFileService.updateStatus(id, 1);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int thoroughDelete(String id) {
        SysFile file = sysFileService.findById(id);
        sysFileService.delete(id);
        if (file != null) {
            List<SysFile> folderFiles = sysFileService.findByFolderId(file.getFolderId());
            if (CollectionUtils.isEmpty(folderFiles)) {
                sysFileinfoDao.delete(file.getFolderId());
            }
        }
        return 1;
    }

    @Override
    public int emptyRecycled() {
        return sysFileinfoDao.emptyRecycled();
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public SysFileinfo findById(String id) {
        return sysFileinfoDao.findById(id);
    }


    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SysFileinfo> findAll(Map<String, Object> params) {
        List<SysFileinfo> list1 = sysFileinfoDao.findAll1(params);
        List<SysFileinfo> list2 = sysFileinfoDao.findAll2(params);
        if (CollectionUtils.isNotEmpty(list2)) {
            list2.forEach(item -> {
                if (list1.stream().filter(t -> t.getId().equals(item.getId())).count() == 0) {
                    list1.add(item);
                }
            });
        }
        list1.forEach(item -> {
            if (StringUtils.isEmpty(item.getAuthType())) {
                item.setAuthType("1,3");
            }
        });
        return list1;
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<SysFileinfo> findTop5(Map<String, Object> params) {
        return sysFileinfoDao.findTop5(params);
    }

    @Override
    public int upload(String folderId, MultipartFile file) {
        String url = null;
        try {
            url = fileService.upload(file);
            SysFileinfo fileinfo = new SysFileinfo();
            fileinfo.setFolderId(folderId);
            fileinfo.setIsShare(0);
            fileinfo.setName(file.getOriginalFilename());
            fileinfo.setFiles(url);
            fileinfo.setCreateTime(new Date());
            fileinfo.setSize(file.getSize());
            fileinfo.setDownloadCount(0);
            fileinfo.setExt(FileUtil.getFileExtension(new URL(url)));
            save(fileinfo);
        } catch (IOException e) {
            log.error("上传文件失败[{}]", e.getMessage());
        }
        return 1;
    }

    @Override
    public int share(String id, List<SysFileinfoAuthorize> fileinfoAuthorizes, Integer isShare) {

        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
        SysFile file = sysFileService.findById(id);
        Assert.notNull(file, "找不到文件");
        SysFileinfo fileinfo = sysFileinfoDao.findById(file.getFolderId());
        Assert.isTrue(loginUser.getId().equals(fileinfo.getCreateUserid()), "您无权分享该文件");

        fileinfoAuthorizeDao.deleteByFileinfoId(id);
        for (SysFileinfoAuthorize authorize : fileinfoAuthorizes) {
            authorize.setFileinfoId(id);
            if (authorize.getAuthType() == null) {
                authorize.setAuthType("1,3");
            }
            fileinfoAuthorizeDao.save(authorize);
        }
        int count = 0;
        fileinfo.setIsShare(isShare);
        fileinfo.setShareTime(new Date());
        count = sysFileinfoDao.update(fileinfo);
        return count;
    }

    @Override
    public int move(String id, String moveFolderId) {
        SysFileinfo fileinfo = sysFileinfoDao.findById(id);
        fileinfo.setFolderId(moveFolderId);
        int count = sysFileinfoDao.update(fileinfo);
        return count;
    }
}
